package com.echo.servlet.ArticleServlet;

import com.echo.entity.Article;
import com.echo.entity.Comment;
import com.echo.exception.ArticleException;
import com.echo.exception.CommentException;
import com.echo.service.ArticleService;
import com.echo.service.CommentService;
import com.echo.servlet.BaseServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/article-detail")
public class ArticleDetailServlet extends BaseServlet {
    private static final Logger logger = LoggerFactory.getLogger(ArticleDetailServlet.class);
    private final ArticleService articleService = new ArticleService();
    private final CommentService commentService = new CommentService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("======== 开始处理文章详情请求 ========");
        System.out.println("请求URI: " + request.getRequestURI());
        System.out.println("请求方法: " + request.getMethod());
        System.out.println("上下文路径: " + request.getContextPath());
        
        try {
            // 1. 获取文章ID参数
            String idStr = request.getParameter("id");
            System.out.println("获取到的文章ID参数: " + idStr);
            
            if (idStr == null || !idStr.matches("\\d+")) {
                System.out.println("文章ID参数无效，重定向到文章列表页");
                response.sendRedirect(request.getContextPath() + "/article-list");
                return;
            }
            
            Integer articleId = Integer.parseInt(idStr);
            System.out.println("解析后的文章ID: " + articleId);

            // 2. 获取评论页码（默认第1页）
            String pageStr = request.getParameter("commentPage");
            System.out.println("获取到的评论页码参数: " + pageStr);
            
            Integer currentPage = (pageStr == null || !pageStr.matches("\\d+")) ? 1 : Integer.parseInt(pageStr);
            System.out.println("解析后的评论页码: " + currentPage);

            // 3. 查询文章详情
            System.out.println("开始查询文章详情，文章ID: " + articleId);
            Article article = articleService.findById(articleId);
            System.out.println("查询文章详情结果: " + (article != null ? "成功" : "失败（文章不存在）"));
            
            // 检查文章是否存在
            if (article == null) {
                System.out.println("文章不存在，重定向到文章列表页");
                response.sendRedirect(request.getContextPath() + "/article-list");
                return;
            }
            
            // 增加文章阅读量
            System.out.println("开始增加文章阅读量，文章ID: " + articleId);
            boolean incrementSuccess = articleService.incrementViewCount(articleId);
            System.out.println("增加阅读量结果: " + (incrementSuccess ? "成功" : "失败"));
            
            // 记录文章的基本信息
            System.out.println("文章标题: " + article.getTitle() + ", 作者: " + article.getAuthorUsername());
            
            // 确保htmlContent不为空，直接使用已转换好的HTML内容
            // HTML内容已经在发布和编辑时通过MarkdownUtils转换完成
            if (article.getHtmlContent() == null || article.getHtmlContent().trim().isEmpty()) {
                System.out.println("文章htmlContent为空，设置默认内容");
                article.setHtmlContent("<p>暂无内容</p>");
            }
            
            request.setAttribute("article", article);
            System.out.println("已将文章对象设置到request属性中");

            // 4. 获取文章评论数据（使用CommentService）
            try {
                System.out.println("开始获取文章评论数据，文章ID: " + articleId + ", 页码: " + currentPage);
                Map<String, Object> commentPageData = commentService.getCommentsByArticleId(articleId, currentPage);
                System.out.println("获取评论数据成功，返回的Map键: " + commentPageData.keySet());
                
                // 记录评论数据中的各个值
                int commentListSize = commentPageData.get("comments") != null ? ((List<?>)commentPageData.get("comments")).size() : 0;
                System.out.println("评论列表大小: " + commentListSize);
                System.out.println("总页数: " + commentPageData.get("totalPages"));
                System.out.println("当前页码: " + commentPageData.get("currentPage"));
                System.out.println("总评论数: " + commentPageData.get("totalComments"));
                
                request.setAttribute("comments", commentPageData.get("comments"));
                request.setAttribute("totalPages", commentPageData.get("totalPages"));
                request.setAttribute("currentPage", commentPageData.get("currentPage"));
                request.setAttribute("totalComments", commentPageData.get("totalComments"));
                
                List<Comment> commentList = (List<Comment>) commentPageData.get("comments");
                System.out.println("获取文章评论成功，文章ID: " + articleId + ", 页码: " + currentPage + ", 评论数: " + commentList.size());
            } catch (CommentException e) {
                System.out.println("获取文章评论失败，文章ID: " + articleId + ", 页码: " + currentPage);
                System.out.println("异常信息: " + e.getMessage());
                e.printStackTrace();
                // 设置默认值，确保页面仍能正常显示
                request.setAttribute("comments", new ArrayList<>());
                request.setAttribute("totalPages", 1);
                request.setAttribute("currentPage", 1);
                request.setAttribute("totalComments", 0);
            }

            // 5. 使用BaseServlet的forward方法转发到详情页，确保session信息被传递
            System.out.println("准备转发到详情页");
            forward(request, response, "/article-detail.html");
            System.out.println("转发完成");
        } catch (Exception e) {
            System.out.println("处理文章详情请求时发生未捕获异常");
            System.out.println("异常信息: " + e.getMessage());
            e.printStackTrace();
            
            // 直接在页面上显示错误信息，便于调试
            response.setContentType("text/html;charset=UTF-8");
            java.io.PrintWriter out = response.getWriter();
            out.println("<html><head><title>错误信息</title></head><body>");
            out.println("<h2>处理请求时发生错误</h2>");
            out.println("<p>错误信息: " + e.getMessage() + "</p>");
            out.println("<pre>");
            e.printStackTrace(out);
            out.println("</pre>");
            out.println("<a href='javascript:history.back()'>返回</a>");
            out.println("</body></html>");
            out.flush();
            out.close();
        } finally {
            System.out.println("文章详情请求处理结束");
        }
    }
}